// scripts/deploy1.js
const { ethers } = require("hardhat");

async function main() {
    const [deployer] = await ethers.getSigners();
    
    console.log("Deploying contracts with the account:", deployer.address);

    // 部署 Mock LINK Token 合约（如果需要）
    // const LinkToken = await ethers.getContractFactory("LinkToken");
    // const linkToken = await LinkToken.deploy();
    // await linkToken.deployed();
    // console.log("Mock LINK Token deployed to:", linkToken.address);

    // 部署 Mock VRF Coordinator 合约
    const MockVRFCoordinator = await ethers.getContractFactory("MockVRFCoordinator");
    const mockVRFCoordinator = await MockVRFCoordinator.deploy(deployer.address); // 传入 LINK Token 地址
    await mockVRFCoordinator.deployed();
    console.log("Mock VRF Coordinator deployed to:", mockVRFCoordinator.address);

    try {
        // 获取 RandomNumber 合约工厂
        const RandomNumber = await ethers.getContractFactory("RandomNumber");
        
        // 部署 RandomNumber 合约，传入 Mock 合约地址
        const randomNumber = await RandomNumber.deploy(mockVRFCoordinator.address, deployer.address);
        console.log("Deploying RandomNumber contract...", randomNumber);
        
        // 检查是否有 deployTransaction
        if (!randomNumber.deployTransaction) {
            console.error("Deploy transaction is undefined.");
            throw new Error("Deploy transaction is undefined.");
        }

        // 获取交易哈希并打印
        const txHash = randomNumber.deployTransaction.hash;
        console.log("Transaction hash:", txHash);

        // 等待交易确认并获取交易收据
        const receipt = await randomNumber.deployTransaction.wait();
        console.log("Transaction confirmed. Receipt:", receipt);

        // 打印合约地址
        console.log("RandomNumber deployed to:", randomNumber.address);
    } catch (error) {
        console.error("Error deploying contract:", error);
    }
}

main()
    .then(() => process.exit(0))
    .catch(error => {
        console.error(error);
        process.exit(1);
    });